package com.cyz.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cyz.config.CosClientConfig;

import com.cyz.exception.BusinessException;
import com.cyz.exception.ErrorCode;
import com.cyz.exception.ThrowUtils;
import com.cyz.model.dto.file.UploadPictureResult;
import com.cyz.model.entity.Picture;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 文件服务
 * @Deprecated 已废弃，改用upload包模板方法优化
 */
@Slf4j
@Service
//@Deprecated // 用来标识该类已经废弃
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    /**
     * 上传并解析图片
     *
     * @param multipartFile    图片文件
     * @param uploadPathPrefix 上传图片的路径前缀
     * @return 解析完成的信息
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 校验图片
        validFile(multipartFile);

        // 拼接图片地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = multipartFile.getOriginalFilename();
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, originalFilename);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);

        // 图片上传
        File file = null;
        try {
            // 将文件转换成File格式,临时存储到本地；
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);

            // 上传到cos对象存储服务器中
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            //获取图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            String format = imageInfo.getFormat();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            double picScale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();

            // 封装图片信息
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadPath);
            uploadPictureResult.setName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(format);
            // 返回图片信息
            return uploadPictureResult;
        } catch (IOException e) {
            log.info("图片上传失败,filePath = {}", uploadPath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 清理临时文件
            if (file != null) {
                boolean deleteResult = file.delete();
                if (!deleteResult) {
                    log.info("临时文件删除失败,filePath = {}", uploadPath);
                }
            }
        }
    }

    /**
     * 图片校验
     *
     * @param multipartFile 图片文件
     */
    private void validFile(MultipartFile multipartFile) {
        // 判断文件是否为空
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "图片为空");
        // 判断文件大小
        final long ONE_M = 1024 * 1024L;
        long size = multipartFile.getSize();
        ThrowUtils.throwIf(size > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "图片大小不能超过2M");
        // 校验文件格式
        List<String> ALLOW_FORMAT_LIST = Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".svg");
        // 获取文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "不支持该格式");
    }

    /**
     * 删除对象
     *
     * @param url 路径（含域名）
     */
    public void deleteObj(String url) {
        if (url != null && !url.isEmpty()) {
            // 去掉域名
            String key = StrUtil.removePrefix(url, cosClientConfig.getHost());
            cosManager.deleteObject(key);
        }
    }

}
